﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using org.apache.zookeeper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OZ_SupOrderDetailInterfaceBusiness_2 : OZInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption OZ_Query { get; set; }

        //订单编号列表
        public List<string> BundleiIdList { get; set; }
        public OZ_SupOrderDetailInterfaceBusiness_2()
        {
            this.InterfaceName = "Ozon交货申请明细2";
            //索引字段
            this.MapFields = GetMapField("OZ_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            OZ_Query = this.interfaceOption.Where(x => x.OperateType == "OZ_Query").First();

            BundleiIdList = new List<string>();
            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LX_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, OZ_NoQueryEventArgs LX_NoQueryEventArgs)
        {
            //API请求是否成功
            LX_NoQueryEventArgs.Success = LX_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {
            try
            {

                //设置请求头参数
                var key = JObject.Parse(OZ_Query.TargetLoginData);
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Client-Id", key["Client-Id"].Value<string>());
                headers.Add("Api-Key", key["Api-Key"].Value<string>());
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                //queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "limit").First().SourceField.ToInt();
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {
            //获取请求的数据
            //List<int> orders = (List<int>)queryEventArgs.CustomData;
            OZ_ReqDTO data = new OZ_ReqDTO();
            data.order_ids = this.BundleiIdList;
            queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                SupOrderDetailDTO result = (SupOrderDetailDTO)JsonConvert.DeserializeObject<SupOrderDetailDTO>(queryEventArgs.ResultStr);
                //if (result.items.Count > 0)
                queryEventArgs.Success = true;
                queryEventArgs.Rows = result.items;
                queryEventArgs.Page.Complete = true;
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async Task<List<SupOrderDetail>> ExecuteInterface(List<OZ_SupOrder> supOrderList)
        {
            List<SupOrderDetail> supOrderDetailList = new List<SupOrderDetail>();
            foreach (var item1 in supOrderList)
            {
                this.BundleiIdList.Clear();
                foreach (var item2 in item1.supplies)
                {
                    this.BundleiIdList.Add(item2.bundle_id);
                    var detailList = await this.QueryAsync<SupOrderDetail>(this.OZ_Query, SqlDb);
                    if (!detailList.IsNullOrEmpty())
                    {
                        foreach (var item3 in detailList)
                        {
                            item3.seller = "2513164";//Ozon-Tecasa
                            item3.supply_order_number = item1.supply_order_number;
                            item3.creation_date = item1.creation_date;
                            item3.state = item1.state;
                            item3.dropoff_warehouse_name = item1.dropoff_warehouse_name;
                            item3.dropoff_warehouse_address = item1.dropoff_warehouse_address;
                            var s = item1.timeslot.value.timezone_info.offset.IsNullOrEmpty() ? 0 : item1.timeslot.value.timezone_info.offset.Replace("s", "").ToInt();
                            item3.timeslot = item1.timeslot.value.timeslot.to.IsNullOrEmpty() ? "" : item1.timeslot.value.timeslot.to.ToDateTime().AddHours(-8).AddSeconds(s).ToString();
                            item3.creation_date = item1.creation_date.IsNullOrEmpty() ? "" : DateTime.ParseExact(item1.creation_date, "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString();
                            item3.ID = item3.supply_order_number + item3.sku;
                        }
                    }
                    supOrderDetailList.AddRange(detailList);
                }
            }
            return supOrderDetailList;


        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            //ExecuteInterface();
        }
    }

}
